package com.xinyue.ext.reader.bean;

import java.util.List;

import org.dom4j.Element;
import org.dom4j.Node;

import com.xinyue.ext.data.FieldData;
import com.xinyue.ext.exception.BeanException;
import com.xinyue.ext.reader.ParamHolder;
import com.xinyue.ext.util.StringUtil;

public class RelyProcess extends BeanContext{
	//私有构造器
	private RelyProcess() {
	}
	//私有内部类
	private static class SingletonHolder{
        private static RelyProcess instance = new RelyProcess();  
    }
	/**
	 * 获得实例对象
	 * @param holder 
	 */
	public static RelyProcess getInstance(ParamHolder holder) {
		BeanContext.holder = holder;
		return SingletonHolder.instance;
	}

	
	/**
	 * 读取many和one标签数据
	 * param e entity
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void read(Element e) throws BeanException {
		List<Element> many = e.elements(many_);
		List<Element> one = e.elements(one_);
		
		relyRead(many, many_);
		relyRead(one, one_);
	}

	/**
	 * 验证Entity合法性
	 */
	private void relyRead(List<Element> rely, String flag) throws BeanException {
		//没有此标签则返回
		if(rely == null || rely.size() == 0) {
			return;
		}
		
		for (Element m: rely) {
			String name = m.attributeValue(name_);
			if(StringUtil.isNull(name)) {
				throw new BeanException("many或one标签的name属性未定义或其值为空", holder.getException());
			}
			
			String entity = m.attributeValue(entity_);
			//验证entity是否合法
			Node n = m.selectSingleNode("/build-mapping/entity[@name='" + entity + "']");
			if(n == null) {
				throw new BeanException("many或one标签的entity属性值非法:" + entity, holder.getException());
			}
			
			FieldData field = new FieldData();
			field.setAnn_transient(true);
			field.setName(name);
			
			if(many_.equals(flag)) {
				field.setType("List<" + entity + ">");
				holder.getBeanImpt().add("java.util.List");
			}else if(one_.equals(flag)) {
				field.setType(entity);
			}
			
			//添加至属性集
			holder.getEntity().getFields().add(field);
			holder.getBeanImpt().add(holder.getEntity().getBeanPackage() + "." + entity);
		}
		
		holder.getBeanImpt().add("javax.persistence.Transient");
	}
}
